<script setup>

import RoleApi from '@/api/role.js'
import MenuApi from '@/api/menu.js'

const queryFormRef = ref()
const roleFormRef = ref()
const permTreeRef = ref()

const loading = ref(false)
const ids = ref([])
const total = ref(0)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
})

// 角色表格数据
const roleList = ref()
// 菜单权限下拉
const menuPermOptions = ref([])

// 权限树展开与收缩
const isExpanded = ref(true)
// 权限分配父子联动
const parentChildLinked = ref(true)

// 弹窗
const dialog = reactive({
  title: '',
  visible: false
})

// 删除角色弹窗
const delDialog = reactive({
  title: '',
  visible: false,
  force: false,
  roleIds: []
})
// 角色表单
const formData = reactive({
  sort: 1,
  status: 1,
  code: '',
  name: ''
})

const rules = reactive({
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
  // dataScope: [{ required: true, message: "请选择数据权限", trigger: "blur" }],
  status: [{ required: true, message: '请选择状态', trigger: 'blur' }]
})

const checkedRole = ref({
  id: null,
  name: ''
})
const assignPermDialogVisible = ref(false)

/*查询*/
const getList = async () => {
  loading.value = true
  const data = await RoleApi.listPaged(queryParams)
  roleList.value = data.rows
  total.value = data.total
  loading.value = false
}

// 打开弹窗
function handleOpenDialog(roleId) {
  dialog.visible = true
  if (roleId) {
    dialog.title = '修改角色'
    RoleApi.getInfo(roleId).then(({ data }) => {
      Object.assign(formData, data)
    })
  } else {
    dialog.title = '新增角色'
  }
}

// 删除角色，对话框
function openDelDialog(roleId) {
  const roleIds = [roleId || ids.value]
  if (!roleIds) {
    ElMessage.warning('请勾选删除项')
    return
  }
  delDialog.roleIds = roleIds
  delDialog.visible = true
}

// 删除角色，提交
function deleteRole() {
  RoleApi.del(delDialog.roleIds, delDialog.force).then(() => {
    ElMessage.success('删除成功')
    getList()
  }).finally(() => {
    delDialog.visible = false
  })
}

// 打开分配权限
async function handleOpenAssignPermDialog(row) {
  const roleId = row.id
  if (roleId) {
    assignPermDialogVisible.value = true
    loading.value = true

    checkedRole.value.id = roleId
    checkedRole.value.name = row.name

    // 获取所有的菜单
    menuPermOptions.value = (await MenuApi.options()).data
    console.log(menuPermOptions.value)

    // 回显角色已拥有的菜单
    RoleApi.getRoleMenuIds(roleId)
      .then(({ data }) => {
        const checkedMenuIds = data || []
        checkedMenuIds.forEach((menuId) =>
          permTreeRef.value.setChecked(menuId, true, false)
        )
      })
      .finally(() => {
        loading.value = false
      })
  }
}

// 分配权限提交
function handleAssignPermSubmit() {
  const roleId = checkedRole.value.id;
  if (roleId) {
    const checkedMenuIds = permTreeRef
      .value.getCheckedNodes(false, true)
      .map((node) => node.id);
    loading.value = true;
    RoleApi.assignMenus(roleId, checkedMenuIds)
      .then(() => {
        ElMessage.success("分配权限成功");
        assignPermDialogVisible.value = false;
        getList();
      })
      .finally(() => {
        loading.value = false;
      });
  }
}


// 角色保存提交
function handleSubmit() {
  roleFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      const roleId = formData.id
      if (roleId) {
        RoleApi.edit(formData)
          .then(() => {
            ElMessage.success('修改成功')
            handleCloseDialog()
            getList()
          })
          .finally(() => (loading.value = false))
      } else {
        RoleApi.add(formData)
          .then(() => {
            ElMessage.success('新增成功')
            handleCloseDialog()
            getList()
          })
          .finally(() => (loading.value = false))
      }
    }
  })
}

function rest() {
  roleFormRef.value.resetFields()
  roleFormRef.value.clearValidate()
}

// 关闭表单弹窗
function handleCloseDialog() {
  dialog.visible = false
  rest()
}

// 行选中事件
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
}

getList()
</script>

<template>
  <div class="app-container">
    <!--    <div class="search-container">-->
    <!--      <el-form ref="queryFormRef" :model="queryParams" :inline="true">-->
    <!--        <el-form-item prop="keywords" label="关键字">-->
    <!--          <el-input-->
    <!--            v-model="queryParams.keywords"-->
    <!--            placeholder="角色名称"-->
    <!--            clearable-->
    <!--            @keyup.enter="handleQuery"-->
    <!--          />-->
    <!--        </el-form-item>-->

    <!--        <el-form-item>-->
    <!--          <el-button type="primary" @click="handleQuery"-->
    <!--          ><i-ep-search />搜索</el-button-->
    <!--          >-->
    <!--          <el-button @click="handleResetQuery"><i-ep-refresh />重置</el-button>-->
    <!--        </el-form-item>-->
    <!--      </el-form>-->
    <!--    </div>-->

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="handleOpenDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="openDelDialog()"
        >
          <i-ep-delete />
          删除
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="roleList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="角色名称" prop="name" min-width="100" />
        <el-table-column label="角色编码" prop="code" width="150" />

        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="排序" align="center" width="80" prop="sort" />

        <el-table-column fixed="right" label="操作" width="300">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDelDialog(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleOpenAssignPermDialog(scope.row)"
            >
              <i-ep-position />
              分配权限
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="$router.push('/system/role-auth/user/' + scope.row.id)"
            >
              <i-ep-position />
              分配用户
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="roleFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入角色编码" />
        </el-form-item>

        <!--        <el-form-item label="数据权限" prop="dataScope">-->
        <!--          <el-select v-model="formData.dataScope">-->
        <!--            <el-option :key="0" label="全部数据" :value="0" />-->
        <!--            <el-option :key="1" label="部门及子部门数据" :value="1" />-->
        <!--            <el-option :key="2" label="本部门数据" :value="2" />-->
        <!--            <el-option :key="3" label="本人数据" :value="3" />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            :min="0"
            style="width: 100px"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--删除角色弹窗-->
    <el-dialog
      v-model="delDialog.visible"
      title="是否要删除选中角色"
      width="500"
    >
      <div class="upload__tip">
        <el-checkbox v-model="delDialog.force" />
        权限已分配时强制删除
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="delDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="deleteRole">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配权限弹窗 -->
    <el-drawer
      v-model="assignPermDialogVisible"
      :title="'【' + checkedRole.name + '】权限分配'"
      size="500"
    >
      <div class="flex-x-between" style="align-items: center; display: flex; justify-content: space-between">
        <el-input
          v-model="permKeywords"
          clearable
          class="w-[200px]"
          style="width: 200px;"
          placeholder="菜单权限名称"
        >
          <template #prefix>
            <i-ep-search />
          </template>
        </el-input>

        <div style="display: flex; justify-content: center; align-items: center">
          <el-button type="primary" size="small" plain @click="togglePermTree"
          >
            <i-ep-switch />
            {{ isExpanded ? '收缩' : '展开' }}
          </el-button
          >
          <el-checkbox
            v-model="parentChildLinked"
            @change="handleparentChildLinkedChange"
            style="margin-left: 1%"
          >父子联动
          </el-checkbox>

          <el-tooltip placement="bottom">
            <template #content>
              如果只需勾选菜单权限，不需要勾选子菜单或者按钮权限，请关闭父子联动
            </template>
            <i-ep-QuestionFilled
              style="margin-left: 5px"
              class="ml-1 color-[--el-color-primary] inline-block cursor-pointer"
            />
          </el-tooltip>
        </div>
      </div>
      <el-tree
        ref="permTreeRef"
        node-key="id"
        show-checkbox
        :data="menuPermOptions"
        :default-expand-all="true"
        :check-on-click-node="true"
        :check-strictly="!parentChildLinked"
        class="mt-5"
        style="margin-top: 5%"
      >
        <template #default="{ data }">
          {{ data.name }}
        </template>
      </el-tree>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleAssignPermSubmit"
          >确 定
          </el-button
          >
          <el-button @click="assignPermDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped>
</style>
